/** @format */

import React, {useState, useEffect} from 'react';
import Link from 'next/link';
import {blogList} from './index.styl';
import {user} from '@/api/user';
import MarkdownIt from 'markdown-it';
import {useRouter} from 'next/router';

interface IProp {
  [props: string]: any;
}

interface IState {
  curPage: number;
  els: JSX.Element | null;
}

interface IArticle {
  id: string;
  title: string;
  markdown: string;
}

interface IBlogListData {
  articleList: IArticle[];
  isNextPage: boolean;
}

interface IQuery {
  id: string;
  [props: string]: any;
}

interface IPreviewNextPageProps {
  curPage: number;
  hasNextPage: boolean;
}

const PreviewNextPage = (props: IPreviewNextPageProps) => {
  const {curPage, hasNextPage} = props;
  const previous =
    curPage > 1 ? (
      <Link href={`/fragment/${curPage - 1}`}>
        <a className="interactive">上一页</a>
      </Link>
    ) : (
      ''
    );
  const next = hasNextPage ? (
    <Link href={`/fragment/${curPage + 1}`}>
      <a className="interactive">下一页</a>
    </Link>
  ) : (
    ''
  );

  return (
    <div className="tool-bar">
      {previous}
      {next}
    </div>
  );
};

const BlogList: React.FC = () => {
  const router = useRouter();
  const curPage: number = parseInt((router.query as IQuery).id);
  const [data, setData] = useState({articleList: [], isNextPage: false});
  useEffect(() => {
    const getRspData = async () => {
      const [err, blogListData]: any = (await user.getArticleList({page: curPage})) as IBlogListData;
      if (!err) {
        setData(blogListData);
      }
    };

    if (curPage) {
      getRspData();
    }
  }, [curPage]);

  return (
    <div key={Date.now()} className={blogList}>
      <section>
        <ul>
          {data.articleList.map((item: IArticle, index: number) => {
            return (
              <li key={index}>
                <Link href={`/post/${item.id}`}>
                  <a className="post-href" title={item.title}>
                    <h2 className="interactive">{item.title}</h2>
                    <div
                      dangerouslySetInnerHTML={{
                        __html: new MarkdownIt({html: true, breaks: true}).render(item.markdown),
                      }}></div>
                  </a>
                </Link>
              </li>
            );
          })}
        </ul>
      </section>
      <PreviewNextPage curPage={curPage} hasNextPage={data.isNextPage} />
    </div>
  );
};

export default BlogList;
